const fs = require('fs');
const path = require('path');
const log4js = require('log4js');
const mdparse = require('../service/mdparse');
const shell = require('shelljs');



function firstSync(srcPath, destPath) {
  const logger = log4js.getLogger("firstSync");
  // check for the existence of srcPath
  try {
    fs.accessSync(srcPath,fs.constants.F_OK);
  } catch (err) {
    logger.error(err.message);
    return;    
  }

  // check for the existence of destPath
  try {
    fs.accessSync(destPath,fs.constants.F_OK);
  } catch (err) {
    logger.error(err.message);
    return;    
  }

  pathSync(srcPath, destPath);

  //logger.debug(srcPath);
}

function pathSync(srcPath, destPath){
  const logger = log4js.getLogger("pathSync");
  fs.readdir(srcPath,function(err, files){
    if(err){
      logger.error(err.message);
    } else {
      files.forEach(function(fileName){
        if( fileName.substr(0,1) === '.' || fileName.toLowerCase() === 'readme.md') return;

        const fileFullName = path.join(srcPath,fileName);
        const destFileFullPath = path.join(destPath, fileName);
        fs.stat(fileFullName, function(staterr, stats){
          if(staterr){
            logger.error(staterr.message);
          } else {
            if(stats.isFile()){              
              logger.info(`${fileFullName}......`);
              if(path.extname(fileFullName).toLowerCase() == '.md'){
                mdparse(fileFullName,destPath);
              } else {
                fs.copyFile(fileFullName, destFileFullPath,(cpyerr)=>{
                  if(cpyerr){
                    logger.error(`Copy [${fileFullName}] error:${cpyerr.message}`);
                  } else {
                    logger.info(`Copy [${fileFullName}] to [${destFileFullPath}] completed.`)
                  }
                });
              }
            } else if(stats.isDirectory()) {
              if(fileName === 'images'){
                shell.cp('-rfu', fileFullName, destPath);
                logger.info(`Copy [${fileFullName}] to [${destPath}] completed.`)
              }

              // 递归子目录，暂屏蔽
              // if(!fs.existsSync(destFileFullPath)){
              //   fs.mkdirSync(destFileFullPath);
              // }
              // pathSync(fileFullName, destFileFullPath);
            }
          }
        })
      })
    }
  })
}

module.exports.firstSync = firstSync;